<?php


namespace App\Web\Model;

use App\Service\Mailer;
use App\Web\Facades\UserAuth;
use EchoPHP\Facades\Db;
use EchoPHP\Facades\Log;
use EchoPHP\Validator\Validator;
use App\Web\Model\Login as LoginModel;
use App\Web\Model\Role as RoleModel;
use App\Web\Model\Team as TeamModel;

/**
 * 用户管理相关业务逻辑
 * @package App\Web\Model
 */
class User extends Model {
    private $tmpCodeLength = 3;// 临时工号数字长度
    private $defaultpassword = 'abc123';// 默认密码

    /**
     * 查询总记录数
     * @param array $search
     * @return array
     */
    public function getListCount($search = [], $teamCode = null) {
        $field = 'count(1) as count';
        return $this->search($field, $search, 0, 0, '', $teamCode)[0]['count'];
    }

    /**
     * 获取用户列表
     * @param array $search 搜索项  目前有 username(用户名/ID) cname(姓名) leader(上级) status(在职状态) islock(是否锁定)
     * @param int $rowFrom
     * @param int $rowTo
     * @param null $field
     * @return array
     */
    public function getList($search = [], $rowFrom = 0, $rowTo = 0, $field = null, $teamCode = null, $joinRole = false, $joinTeam = false) {
        $field = $field ?? 'userid,username,cname,email,mobilephone,leader,status,islock,lockdate,issuper,downloadcount';
        return $this->search($field, $search, $rowFrom, $rowTo, 'userid ASC', $teamCode, $joinRole, $joinTeam);
    }

    /**
     * 获取带角色信息的用户明细信息
     * @param $userId
     * @return array|mixed
     */
    public function getInfoWithRole($userId) {
        if ($userId <= 0) {
            return [];
        }
        $field = 'userid,username,cname,defaultpassword,email,position,department,level,mobilephone,leader,area,level,leadername,jointime,islock,lockdate,teamid,teamcode,teamrole,User.issuper,User.status,User.roleid,rolename,rights,Role.issuper as superrole,User.area,User.level,User.jointime,mobileauth';
        $sql = 'SELECT ' . $field . ' FROM User LEFT JOIN Role ON User.roleid=Role.roleid WHERE userid=? AND Role.status=?';
        $var = [$userId, '01'];
        $userInfo = Db::selectOne($sql, $var);

        return is_null($userInfo) ? [] : $userInfo;
    }

    /**
     * 关联查询团队信息
     * @param $userId
     * @return array|mixed
     */
    public function getInfoWithTeam($userId) {
        if ($userId <= 0) {
            return [];
        }
        $field = 'userid,username,cname,defaultpassword,email,position,department,level,mobilephone,mobileauth,leader,area,level,leadername,jointime,islock,lockdate,User.teamid,teamrole,User.issuper,User.status,User.roleid,teamname,Team.teamcode';
        $sql = 'SELECT ' . $field . ' FROM User LEFT JOIN Team ON User.teamid=Team.teamid WHERE userid=?';
        $var = [$userId];

        $userInfo = Db::selectOne($sql, $var);

        return is_null($userInfo) ? [] : $userInfo;
    }

    /**
     * 获取带角色信息的用户明细信息
     * @param $userName
     * @return array|mixed
     */
    public function getInfoWithRoleByUsername($userName) {
        if (is_null($userName)) {
            return [];
        }
        $field = 'userid,username,password,cname,defaultpassword,email,mobilephone,mobileauth,leader,islock,lockdate,teamid,teamcode,teamrole,User.issuper,User.status,User.roleid,rolename,rights,Role.issuper as superrole,User.area,User.level,User.jointime';
        $sql = 'SELECT ' . $field . ' FROM User LEFT JOIN Role ON User.roleid=Role.roleid WHERE username=? AND Role.status=?';
        $var = [$userName, '01'];

        $userInfo = Db::selectOne($sql, $var);

        return is_null($userInfo) ? [] : $userInfo;
    }

    /**
     * 通过已认证手机号获取带角色信息的用户明细信息
     * @param $mobilePhone 已认证手机号
     * @return array|mixed
     */
    public function getInfoWithRoleByPhone($mobilePhone) {
        if (is_null($mobilePhone)) {
            return [];
        }
        $field = 'userid,username,password,cname,defaultpassword,email,mobilephone,mobileauth,leader,islock,lockdate,teamid,teamcode,teamrole,User.issuper,User.status,User.roleid,rolename,rights,Role.issuper as superrole,User.area,User.level,User.jointime';
        $sql = 'SELECT ' . $field . ' FROM User LEFT JOIN Role ON User.roleid=Role.roleid WHERE mobilephone=? AND mobileauth=? AND Role.status=?';
        $var = [$mobilePhone, 1, '01'];

        $userInfo = Db::selectOne($sql, $var);

        return is_null($userInfo) ? [] : $userInfo;
    }

    /**
     * 获取用户信息
     * @param $userId
     * @param null $field
     * @return array|mixed
     */
    public function getInfo($userId, $field = null) {
        if ($userId <= 0) {
            return [];
        }
        if (empty($field)) {
            $field = 'userid,username,cname,email,mobilephone,leader,islock,lockdate,issuper,status';
        }
        $sql = 'SELECT ' . $field . ' FROM User WHERE userid=?';
        $var = [$userId];
        $userInfo = Db::selectOne($sql, $var);

        return is_null($userInfo) ? [] : $userInfo;
    }

    /**
     * Notes:执行查询
     * @param $field
     * @param array $search
     * @param int $rowFrom
     * @param int $rowTo
     * @param string $orderBy
     * @return array
     */
    public function search($field, $search = [], $rowFrom = 0, $rowTo = 0, $orderBy = '', $teamCode = null, $joinRole = false, $joinTeam = false) {
        $sql = 'SELECT ' . $field . ' FROM User';
        $var = [];
        $where = [];

        //查询工号
        if (isset($search['username']) && $search['username'] != '') {
            $stringArr = $this->modifySearchArr($search['username']);
            $stringArr = array_slice($stringArr, 0, 10);
            $inFlag = substr(str_repeat('?,', (count($stringArr))), 0, -1);
            $where[] = 'username in (' . $inFlag . ')';
            $var = array_merge($var, $stringArr);
        }
        //查询用户ID
        if (isset($search['userid']) && !empty($search['userid'])) {
            $stringArr = $this->modifySearchArr($search['userid']);
            if (is_numeric($stringArr[0])) {
                $stringArr = array_slice($stringArr, 0, 10);
                $inFlag = substr(str_repeat('?,', (count($stringArr))), 0, -1);
                $where[] = 'userid in (' . $inFlag . ')';
                $var = array_merge($var, $stringArr);
            } else {
                $where[] = 'cname LIKE ?';
                $var[] = '%' . $search['userid'] . '%';
            }
        }
        //id 使用wherein 查找
        if (isset($search['ids']) && !empty($search['ids'])) {
            $inFlag = substr(str_repeat('? ,', (count($search['ids']))), 0, -1);
            $where[] = 'userid in ( ' . $inFlag . ' )';
            $var += $search['ids'];
        }
        //查询姓名
        /*if (isset($search['cname']) && !empty($search['cname'])) {
            $where[] = 'cname LIKE ?';
            $var[] = '%' . $search['cname'] . '%';
        }*/
        //查询在职状态
        if (isset($search['status']) && in_array($search['status'], ['01', '06'])) {
            $where[] = 'status = ?';
            $var[] = $search['status'];
        }
        //查询锁定
        if (isset($search['islock']) && in_array($search['islock'], ['0', '1'])) {
            $where[] = 'islock = ?';
            $var[] = $search['islock'] == 1 ? 1 : 0;
        }

//        if (isset($search['roleid'])) {              //有这个标记表示查看用户详细信息，找出对应权限
//            $sql = 'SELECT ' . $field . ' FROM User,Role';
//            $where[] = 'User.roleid=Role.roleid';
//        }

        //查询所在团队
        if (!empty($search['teamid'])) {
            $where[] = 'teamid = ?';
            $var[] = $search['teamid'];
        }
        //查询所在团队
        if (isset($search['teamcode']) && strlen($search['teamcode']) > 0) {
            $withChild = isset($search['withchild']) && $search['withchild'] == 1 ? true : false;
            if ($withChild) {
                $where[] = 'User.teamcode LIKE ?';
                $var[] = $search['teamcode'] . '%';
            } else {
                $where[] = 'User.teamcode = ?';
                $var[] = $search['teamcode'];
            }
        }elseif (isset($teamCode) && !empty($teamCode)) {
            $where[] = 'User.teamcode like ?';
            $var[] = $teamCode . '%';
        }
        //查询团队身份
        if (!empty($search['teamrole']) && in_array($search['teamrole'], [1, 2])) {
            $where[] = 'User.teamrole = ?';
            $var[] = $search['teamrole'];
        }
        //查询团队成员
        if (isset($search['teammember']) && $search['teammember'] == 1) {
            $where[] = 'User.teamid > ?';
            $var[] = 0;
        }
        //超级管理员
        if (isset($search['issuper'])) {
            $where[] = 'issuper = ?';
            $var[] = $search['issuper'];
        }

        //地区
        if (isset($search['area']) && $search['area'] == 0) {
            $where[] = 'area like ?';
            $var[] = '%' . $search['area'] . '%';
        }

        if (isset($search['level']) && $search['level']) {
            $where[] = 'level = ?';
            $var[] = $search['level'];
        }

        if (isset($search['roleid']) && $search['roleid']) {
            $where[] = 'User.roleid = ?';
            $var[] = $search['roleid'];
        }

        if ($joinRole) {
            $sql .= ' left join Role on User.roleid = Role.roleid ';
        }
        if ($joinTeam) {
            $sql .= ' left join Team on User.teamid = Team.teamid ';
        }

        if (!empty($where)) {
            $sql .= ' WHERE ' . implode(' AND ', $where);
        }

        $sql .= empty($orderBy) ? ' ORDER BY userid DESC' : (' ORDER BY ' . $orderBy);

        return Db::select($sql, $var, $rowFrom, $rowTo);
    }

    /**
     * 锁定/解锁 用户，只有在职用户可以操作，离职用户不可操作
     * @param $oprid
     * @param $userid
     * @param $lockStatus
     * @return false|array
     * @throws \Exception
     */
    public function lock($oprid, $userid, $lockStatus) {
        if ($lockStatus == 1) {
            $lockAfter = 0;
            $lockBefore = 1;
        } else {
            $lockAfter = 1;
            $lockBefore = 0;
        }

        $sql = 'UPDATE User SET islock=?,lockdate=' . ($lockStatus == 1 ? 'NULL' : 'Now()') . ',updatedate=Now() WHERE userid=? AND islock=? AND issuper=?';
        $var = [$lockAfter, $userid, $lockBefore, 0];

        $lockResult = Db::update($sql, $var);
        return $lockResult;
    }

    /**
     * 检查用户名是否已存在
     * @param $userName
     * @param int $userId
     * @return bool
     */
    public function chkUsername($userName, $userId = 0) {
        $sql = 'SELECT userid FROM User WHERE username=?';
        $userNameInfo = Db::select($sql, [strtolower($userName)]);
        if (empty($userNameInfo)) {
            return true;
        }
        if (count($userNameInfo) > 1) {
            return false;
        }
        return $userNameInfo[0]['userid'] == $userId;
    }

    /**
     * 检查姓名是否存在
     * @param $cname
     * @param int $userId
     * @return bool
     */
    public function chkCname($cname, $userId = 0) {
        $sql = 'SELECT userid FROM User WHERE cname=?';
        $userNameInfo = Db::select($sql, [$cname]);
        if (empty($userNameInfo)) {
            return true;
        }
        if (count($userNameInfo) > 1) {
            return false;
        }
        return $userNameInfo[0]['userid'] == $userId;
    }

    /**
     * 已存在用户ID进行编辑保存/不存在用户ID则新增用户
     * @param string $username 用户名
     * @param string $cname 姓名
     * @param int $roleId 用户角色ID
     * @param $teamCode
     * @param $teamRole
     * @param $level
     * @param $leader
     * @param $entryDate 入职时间
     * @param $branch 地区
     * @param $email
     * @param $mobilephone
     * @param $position
     * @param $department
     * @return array   返回结果值
     */
    public function addUser($username, $cname, $roleId, $teamCode, $teamRole, $level, $leader, $entryDate, $branch, $email, $mobilephone, $position, $department, $tmpArea) {
        //$username = strtolower($username);
        $rule = [
            'username|工号' => [
                'number', 'min' => 0, 'max' => 2000000000
            ],
            'cname|姓名' => [
                'required', 'minLength' => '1', 'maxLength' => '20'
            ],
            'level|级别' => [
                'required'
            ],
            'leader|领导' => [
                'required'
            ],
            'entrydate' => [
                'required', 'dateFormat' => 'Y-m-d'
            ],
            'branch' => [
                'required'
            ],
            'email' => [
                'required', 'email', 'maxLength' => 100, 'regex' => '/.+@51job.com/'
            ],
            'mobilephone|联系方式' => [
                'required', 'telPhone', 'maxLength' => 20
            ],
            'position|职位' => [
                'required', 'maxLength' => 100
            ],
            'department|部门' => [
                'required', 'maxLength' => 100
            ],
        ];
        $msg = [
            'email.regex' => '请填写正确的@51job.com邮箱',
        ];
        $validate = new Validator($rule, $msg);

        $result = $validate->validate([
            'username' => $username,
            'cname' => $cname,
            'level' => $level,
            'leader' => $leader,
            'entrydate' => $entryDate,
            'branch' => $branch,
            'email' => $email,
            'mobilephone' => $mobilephone,
            'position' => $position,
            'department' => $department
        ]);
        if (!$result) {
            $errMessages = $validate->getErrors();
            return ['status' => false, 'message' => '字段校验失败', 'validateFailure' => $errMessages];
        }
        //生成临时工号
        $tmpCode = $this->tmpCode($username, $tmpArea);
        $nonumber = $tmpCode == $username ? 0 : 1;
        $username = $tmpCode;
        //查询用户名是否唯一
        if (false == $this->chkUsername($username)) {
            return ['status' => false, 'message' => '该工号已存在', 'validateFailure' => ['username' => '该工号已存在']];
        }
        //查询用户名是否唯一
        if (false == $this->chkCname($cname)) {
            return ['status' => false, 'message' => '该姓名已存在', 'validateFailure' => ['cname' => '该姓名已存在']];
        }
        //校验角色信息
        $roleModel = new RoleModel();
        $roleInfo = $roleModel->getRoleInfo($roleId);
        if (!$roleInfo['status']) {
            return ['status' => false, 'message' => '字段校验失败', 'validateFailure' => ['roleid' => '请选择所属角色']];
        }
        //校验上级leader信息
        $leaderInfo = $this->getInfo($leader, 'cname,teamcode,teamrole,issuper');
        if (empty($leaderInfo)) {
            return ['status' => false, 'message' => '字段校验失败', 'validateFailure' => ['leader' => '请选择上级领导']];
        }
        //校验团队信息
        $teamModel = new TeamModel();
        $teamInfo = $teamModel->getTeamInfoByCode($teamCode, 'teamid');
        if (!empty($teamInfo)) {
            $saveTeamId = $teamInfo['teamid'];
            $saveTeamCode = $teamCode;
            $saveTeamRole = in_array($teamRole, [1, 2]) ? $teamRole : 1;
        } else {
            return ['status' => false, 'message' => '字段校验失败', 'validateFailure' => ['teamcode' => '请选择团队']];
        }

        if ($leaderInfo['issuper'] != 1 && (substr($leaderInfo['teamcode'], 0, 5) != substr($saveTeamCode, 0, 5) || $leaderInfo['teamrole'] != 2)) {
            return ['status' => false, 'message' => '字段校验失败', 'errorFields' => ['leader' => '所选领导不是当前团队的leader']];
        }

        $password = $this->encryptPwd($username, $this->defaultpassword);
        $sql = 'INSERT into User (username,password,defaultpassword,cname,roleid,status,leader,leadername,createdate,updatedate,teamid,teamcode,teamrole,area,`level`,jointime,email,mobilephone,mobileauth,department,`position`,nonumber,parttimearea)
                VALUES(?,?,?,?,?,?,?,?,Now(),Now(),?,?,?,?,?,?,?,?,?,?,?,?,?)';
        $var = [$username, $password, 1, $cname, $roleId, '01', $leader, $leaderInfo['cname'], $saveTeamId, $saveTeamCode, $saveTeamRole, $branch, $level, $entryDate, $email, $mobilephone, 0, $department, $position, $nonumber, $tmpArea];
        Db::insert($sql, $var);
        $this->createUserEmail($username, $email);
        return ['status' => true, 'message' => '操作成功'];
    }

    /**
     * Notes:已存在用户ID进行编辑保存/不存在用户ID则新增用户
     * @param $userId
     * @param $roleId
     * @param $teamCode
     * @param $teamRole
     * @param $level
     * @param $leader
     * @param $entryDate 入职时间
     * @param $branch 地区
     * @param $email
     * @param $mobilePhone
     * @param $position
     * @param $department
     * @return array
     */
    public function saveUser($userId, $roleId, $teamCode, $teamRole, $level, $leader, $entryDate, $branch, $email, $mobilePhone, $position, $department) {
        $userInfo = $this->getInfoInteam($userId);
        if (empty($userInfo)) {
            return [
                'status' => false,
                'message' => '操作失败',
                'validateFailure' => ['userid' => '用户不存在或无权编辑该用户数据']
            ];
        }
        $rule = [
            'level|级别' => [
                'required'
            ],
            'leader|领导' => [
                'required'
            ],
            'entrydate' => [
                'required', 'dateFormat' => 'Y-m-d'
            ],
            'branch' => [
                'required'
            ],
            'email' => [
                'required', 'email', 'maxLength' => 100, 'regex' => '/.+@51job.com/'
            ],
//            'mobilephone|联系方式' => [
//                'required', 'telPhone', 'maxLength' => 20
//            ],
            'position|职位' => [
                'required', 'maxLength' => 100
            ],
            'department|部门' => [
                'required', 'maxLength' => 100
            ],
        ];
        $msg = [
            'email.regex' => '请填写正确的@51job.com邮箱',
        ];
        $validate = new Validator($rule, $msg);

        $result = $validate->validate([
            'level' => $level,
            'leader' => $leader,
            'entrydate' => $entryDate,
            'branch' => $branch,
            'email' => $email,
//            'mobilephone' => $mobilePhone,
            'position' => $position,
            'department' => $department
        ]);
        if (!$result) {
            $errMessages = $validate->getErrors();
            return ['status' => false, 'message' => '字段校验失败', 'validateFailure' => $errMessages];
        }
        //校验角色信息
        $roleModel = new RoleModel();
        $roleInfo = $roleModel->getRoleInfo($roleId);
        if (!$roleInfo['status']) {
            return ['status' => false, 'message' => '字段校验失败', 'validateFailure' => ['roleid' => '请选择所属角色']];
        }
        //校验团队信息
        $teamModel = new TeamModel();
        $teamInfo = $teamModel->getTeamInfoByCode($teamCode, 'teamid');
        if (!empty($teamInfo)) {
            $saveTeamId = $teamInfo['teamid'];
            $saveTeamCode = $teamCode;
            $saveTeamRole = in_array($teamRole, [1, 2]) ? $teamRole : 1;
        } else {
            return ['status' => false, 'message' => '操作失败', 'validateFailure' => ['roleid' => '请选择所属团队']];
        }
        //校验上级leader信息
        $leaderInfo = $this->getInfo($leader, 'cname');
        if (empty($leaderInfo)) {
            return ['status' => false, 'message' => '字段校验失败', 'validateFailure' => ['leader' => '请选择上级领导']];
        }

        $sql = 'UPDATE User SET roleid=?,updatedate=Now(),teamid=?,teamcode=?,teamrole=?,level=?,leader=?,leadername=?,jointime=?,area=?,email=?,/*mobilephone=?,*/position=?,department=? WHERE userid=? AND issuper=?';
        $var = [$roleId, $saveTeamId, $saveTeamCode, $saveTeamRole, $level, $leader, $leaderInfo['cname'], $entryDate, $branch, $email,/* $mobilePhone, */
            $position, $department, $userId, 0];
        Db::update($sql, $var);

        //强制退出
        $loginModel = new LoginModel();
        $loginModel->excluded(0, $userId, '您的账号已被修改，请重新登录');
        return ['status' => true, 'message' => '操作成功'];
    }

    /**
     * 根据用户id判断其密码是否正确
     * @param $userId
     * @param $password
     * @return bool
     */
    public function chkPasswordByUserId($userId, $password) {
        if (intval($userId) <= 0 || empty($password)) {
            return false;
        }
        $sql = 'SELECT userid,username,password FROM User Where userid=?';
        $var = [intval($userId)];
        $userInfo = Db::selectOne($sql, $var);
        if (empty($userInfo)) {
            return false;
        }
        return $userInfo['password'] == $this->encryptPwd($userInfo['username'], $password);
    }

    /**
     * 使用username和password进行加密处理
     * @param string $userName
     * @param string $password
     * @return string
     * @throws \RuntimeException
     */
    public function encryptPwd($userName, $password) {
        $userName = '';
        $key = env('PASSWORD_AUTH_KEY');
        if (empty($key)) {
            throw new \RuntimeException('密码加密密钥未定义');
        }
        $userName = strtolower($userName);
        return md5(substr(crypt(strrev($userName) . md5($password), substr($key, 3, 2)), 1, 5) . strrev($password) . $key);
    }

    /**
     * 设置默认初始密码，需输入当前操作人密码，并借由username进行加密处理
     * @param $oprId
     * @param $oprPassword
     * @param int $userid
     * @return array
     * @throws \Exception
     */
    public function resetpwd($oprId, $oprPassword, $userid) {
        $userInfo = $this->getInfo($userid, 'userid,username');
        if (empty($userInfo)) {
            return [
                'status' => false,
                'message' => '请确认用户是否存在'
            ];
        }
        if (!$this->chkPasswordByUserId($oprId, $oprPassword)) {
            return [
                'status' => false,
                'message' => '您输入的密码不正确,请重新输入'
            ];
        }

        $userPassword = $this->encryptPwd($userInfo['username'], $this->defaultpassword);
        $sql = 'UPDATE User SET password=?,defaultpassword=?,updatedate=Now() WHERE userid=? AND issuper=?';
        $var = [$userPassword, 1, $userid, 0];
        $result = Db::update($sql, $var);
        if (!$result) {
            return [
                'status' => false,
                'message' => '操作失败'
            ];
        }
        //强制退出
        $loginModel = new LoginModel();
        $loginModel->excluded(0, $userid, '您的密码已被重置，请重新登录');

        //向被重置密码的账户邮箱发送通知邮件
        $mail = new Mailer();
        $sql = 'select email from User where userid = ?';
        $var = [$userid];
        $result = Db::selectOne($sql, $var);
        if (!empty($result)) {
            $email = $result['email'];
            try {
                $mail->isJobsmail(true);
                $mail->setFrom($mail->defaultSender['noreplay']['email'], $mail->defaultSender['noreplay']['name']);
                $mail->addAddress($email);
                $mail->isHTML(true);
                $mail->Subject = 'RPO系统密码重置通知';
                $mail->Body = '您的密码被用户:' . UserAuth::getLoginInfo('username') . '重置，请重新登录系统并设置新密码 ' . 'http://' . config('app.url');
                $mail->setJobsmailFlag(config('mail.flag.common', 0));
                $mail->send();
            } catch (\Exception $e) {
                Log::error('发送重置密码邮件失败,用户id:' . $userid, [$mail->ErrorInfo]);
            }
        } else {
            Log::warning('发送重置密码邮件失败，用户id:' . $userid . '邮箱不存在');
        }

        return [
            'status' => true,
            'message' => '操作成功'
        ];
    }

    public function getTeamLeader() {
        $leader = ['leader' => [], 'superadmin' => []];
        //获取所有leader
        $sql = 'SELECT userid,cname,teamcode,issuper FROM User where (teamrole=? or issuper=?) and status=?';
        $var = [2, 1, '01'];
        $leaders = Db::select($sql, $var);
        foreach ($leaders as $item) {
            if ($item['issuper'] == 1) {
                $leader['superadmin'] = ['userid' => $item['userid'], 'cname' => $item['cname']];
            } else {
                $leader['leader'][substr($item['teamcode'], 0, 5)][] = $item;
            }
        }
        return $leader;
    }

    public function isTeamMember($userId) {
        if (UserAuth::getLoginInfo('issuper') != 1) {
            $sql = 'select teamcode from User where userid=? and status=?';
            $var = [$userId, '01'];
            $userinfo = Db::selectOne($sql, $var);
            if (substr($userinfo['teamcode'], 0, 5) != substr(UserAuth::getLoginInfo('teamcode'), 0, 5)) {
                return false;
            }
        }
        return true;
    }

    //所有用户id
    public function getAllUserId() {
        $sql = 'select userid from User where status = ? and islock = ?';
        return array_column(Db::select($sql, ['01', 0]), 'userid');
    }

    //临时工号生成器
    private function tmpCode($username, $tmpArea) {
        if ($username > 0 || $tmpArea == '') {
            return $username;
        }
        $sql = 'select count(1) as num from User where username like ?';//临时编号不删，不用判断状态
        $num = Db::selectOne($sql, [$tmpArea . '%'])['num'] + 1;
        return $tmpArea . str_pad($num, $this->tmpCodeLength, '0', STR_PAD_LEFT);
    }

    private function createUserEmail($username, $email) {
        $mail = new Mailer();
        try {
            $mail->isJobsmail(true);
            $mail->setFrom($mail->defaultSender['noreplay']['email'], $mail->defaultSender['noreplay']['name']);
            $mail->addAddress($email);
            $mail->isHTML(true);
            $mail->Subject = 'RPO系统成功开通用户通知';
            $mail->Body = '已成功为您开通RPO账号，请登录' . config('app.host_domain', '') . ' 查看。<br/>工号：' . $username . '<br/>默认密码：' . $this->defaultpassword;
            $mail->setJobsmailFlag(config('mail.flag.common', 0));
            $mail->send();
        } catch (\Exception $e) {
            Log::error('创建' . $username . '用户邮件发送失败: ', [$mail->ErrorInfo]);
        }
    }

    //返回同一大团队下的成员数据
    public function getInfoInteam($userId, $field = null) {
        if ($userId <= 0) {
            return [];
        }
        if (empty($field)) {
            $field = 'userid,username,cname,defaultpassword,email,position,department,level,mobilephone,mobileauth,leader,area,level,leadername,jointime,islock,lockdate,teamid,teamcode,teamrole,User.issuper,User.status,User.roleid,rolename,rights,Role.issuper as superrole,User.area,User.level,User.jointime';
        }
        $sql = 'SELECT ' . $field . ' FROM User LEFT JOIN Role ON User.roleid=Role.roleid WHERE userid=? AND Role.status=?';
        $var = [$userId, '01'];
        //非超管只能查看同一一级团队或默认团队下
        if (UserAuth::getLoginInfo('issuper') != 1) {
            $sql .= ' AND (teamcode like ? or teamid = ?)';
            $var[] = substr(UserAuth::getLoginInfo('teamcode'), 0, 5) . '%';
            $var[] = '1';

        }
        $userInfo = Db::selectOne($sql, $var);

        return is_null($userInfo) ? [] : $userInfo;
    }

    /**
     * 解除用户手机绑定
     * @param $userId
     * @param $oprId
     * @return array
     */
    public function unbindPhone($userId, $oprId) {
        if ($userId <= 0) {
            return [
                'status' => false,
                'message' => '用户id无效'
            ];
        }

        $sql = 'update User set mobileauth=?,updatedate=Now() where userid=? and mobileauth=?';
        $var = [0, $userId, 1];
        $updateResult = Db::update($sql, $var);
        if (!$updateResult) {
            Log::error('用户id:' . $userId . '解除手机绑定失败，操作人id：' . $oprId);
            return [
                'status' => false,
                'message' => '操作失败'
            ];
        } else {
            Log::info('用户id:' . $userId . '解除手机绑定，操作人id：' . $oprId);
            return [
                'status' => true,
                'message' => '操作成功'
            ];
        }
    }
}
